package cn.bluedot.tea.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;


import cn.bluedot.tea.pojo.domain.User;
import cn.bluedot.tea.pojo.vo.RunningLogMessage;
import cn.bluedot.tea.util.DateUtil;

public class RunningLogFilter implements Filter {

	static Logger log = Logger.getLogger(RunningLogFilter.class.getName());

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		String context = req.getContextPath().trim();
		String requestUri = req.getRequestURI().trim();
		
		String path = requestUri.replace(context, "").replaceFirst("/", "");
		
		if(path.equals("") || path == null || path.contains("static") || path.contains("assets")) { //放行忽略项
			chain.doFilter(request, response);
			return;
		}
		
		Long startTime = System.currentTimeMillis();
		chain.doFilter(request, response);
		Long endTime = System.currentTimeMillis();

		String date = DateUtil.getDateTime();
		Integer userId = 0;
		if ((req).getSession().getAttribute("user") != null) {
			User user = (User) (req).getSession().getAttribute("user");
			userId = user.getUserId();
		}
		String URI = (req).getRequestURI();
		Map<String, String[]> requestParams = request.getParameterMap();

		String resultType = (String) response.getContentType();
		if(resultType == null || "".equals(resultType.trim())) {
			resultType = "其他";
		}
		String runningTime = (endTime - startTime) + " ms";
		String userIp = getIpAddress((req));

		RunningLogMessage message = new RunningLogMessage(date, userId, URI, requestParams, resultType, runningTime,
				userIp);

		log.info(message);

	}

	/**
	 * 从request中获取用户IP
	 * 
	 * @param request
	 * @return
	 */
	private static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public void destroy() {
	}

}
